package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.constant.LoginConstant;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.JwtUtil;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Struct;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author zwf
 * @date 2024/3/10 15:05
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // //判断用户是否 登录（ThreadLocal中是否存在用户）
        // if(UserHolder.getUser()==null){
        //     response.setStatus(401);
        //     return false;
        // }
        // return true;

        //令牌校验
        String token = request.getHeader("Authorization");
        try {
            //从redis中获取token
            String redisToken = stringRedisTemplate.opsForValue().get(LoginConstant.KEY_OF_TOKEN_PREFIX+token);
            if(!StringUtils.hasLength(redisToken)){  //说明账号下线或密码修改
                throw new RuntimeException();
            }

            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把token携带的数据存储到ThreadLocal中
            UserDTO userDTO =new UserDTO();
            userDTO.setId(((Integer)(claims.get("id"))).longValue());
            UserHolder.saveUser(userDTO);
            //放行
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("JWT令牌错误。。。");
            response.setStatus(401);
            //不放行
            return false;
        }

    }
}
